﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using Dapper.Mapper;
using PortalWeb.Common.Extensions;
using PortalWeb.Core.Entity;
using PortalWeb.Core.IDao;

namespace PortalWeb.DapperDao.Base
{
    public partial class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private IDbConnection conn = null;
        private readonly string _tableName;

        public BaseRepository()
        {
            conn = SessionFactory.CreateConnection();
            conn.Open();
            _tableName = typeof(T).GetAttributeValue((TableAttribute ta) => ta.Name);
        }

        public void Dispose()
        {
            conn.Close();
        }


        public int Count()
        {
            throw new NotImplementedException();
        }

        public IEnumerable<T> Where(Func<T, bool> func)
        {
            throw new NotImplementedException();
        }

        public long Add(T entity)
        {
           return conn.Insert<T>(entity);
        }

        public T Find(dynamic primaryId)
        {
            return conn.Get<T>(primaryId as object);
        }

        public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
        {
            IEnumerable<T> items = null;

            QueryResult result = DynamicQuery.GetDynamicQuery(_tableName, predicate);

            items = conn.Query<T>(result.Sql, (object) result.Param);
            return items;
        }


        public bool Update(T entity, bool isSave = true)
        {
            throw new NotImplementedException();
        }

        public bool Delete(IList<T> entityList, bool isSave = true)
        {
            throw new NotImplementedException();
        }


        public bool Delete(T entity, bool isSave = true)
        {
            throw new NotImplementedException();
        }

        public int Count(Expression<Func<T, bool>> predicate)
        {
            throw new NotImplementedException();
        }

        public bool Exist(Expression<Func<T, bool>> anyLambda)
        {
            throw new NotImplementedException();
        }


        public T[] LoadPageEntities<TS>(Expression<Func<T, bool>> whereLambda, bool isAsc,
            Expression<Func<T, TS>> orderByLambda, int offset, int limit)
        {
            throw new NotImplementedException();
        }

        public T[] LoadPageEntities(Expression<Func<T, bool>> whereLambda, string order, string sort, int offset,
            int limit)
        {
            throw new NotImplementedException();
        }
    }
}
